package com.redsoil.house.ui.matter.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.redsoil.house.R;
import com.redsoil.house.base.RootActivity;
import com.redsoil.house.model.bean.MessageListVO;
import com.redsoil.house.model.bean.MySection;
import com.redsoil.house.ui.matter.adapter.MatterAdapter;
import com.redsoil.house.ui.matter.contract.MatterContract;
import com.redsoil.house.ui.matter.presenter.MatterPresenter;
import com.redsoil.house.widget.actionbar.MatterTopBar;
import com.redsoil.house.widget.actionbar.MatterTopBarImp;
import com.redsoil.house.widget.bottombar.MatterBottomBar;
import com.redsoil.house.widget.bottombar.MatterBottomBarImp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 确认事项
 */
public class MatterActivity extends RootActivity<MatterPresenter> implements MatterContract.View,MatterTopBarImp,MatterBottomBarImp{

    @BindView(R.id.matter_topbar)
    MatterTopBar matter_topbar;

    @BindView(R.id.matter_edit)
    EditText matter_edit;

    @BindView(R.id.rv_list)
    RecyclerView rv_list;

    @BindView(R.id.matter_bottom_bar)
    MatterBottomBar matter_bottom_bar;

    private String keywords;

    private MatterAdapter matterAdapter;

    @Override
    protected int getLayout() {
        return R.layout.activity_matter;
    }

    @Override
    protected void initEventAndData() {

        super.initEventAndData();

        matter_topbar.setMatterTopBarImp(this);

        matter_bottom_bar.setMatterBottomBarImp(this);

        matter_edit.setOnEditorActionListener(EnterListenter);

        stateLoading();

        doQuert();
    }

    @Override
    public void getMessageListSuccess(MessageListVO messageListVO) {

        if(matterAdapter == null){
            rv_list.setLayoutManager(new LinearLayoutManager(this));

//        rv_list.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));

            matterAdapter = new MatterAdapter(R.layout.matter_list_content_item, R.layout.matter_list_title_item, getSampleData(messageListVO.getDataList()));

            matterAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    MySection mySection = (MySection) adapter.getData().get(position);
                    if (!mySection.isHeader){
                        MessageListVO.DataListBean bean = (MessageListVO.DataListBean) mySection.t;
                        if(bean.getEdit()){
                            bean.setSelected(!bean.getSelected());
                            matterAdapter.notifyItemChanged(position);
                        }else {
                            startActivity(MatterInfoActivity.newInstance(getBaseContext(),bean.getId()));
                        }
                    }
                }
            });

//        matterAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//            }
//        });
            rv_list.setAdapter(matterAdapter);
        }else {
            ToastUtils.showShortToast("操作成功");
            matter_topbar.clear();
            matter_bottom_bar.setVisibility(View.GONE);
            matterAdapter.setNewData(getSampleData(messageListVO.getDataList()));
        }

        stateMain();
    }

    @Override
    public void back() {
        finish();
    }

    @Override
    public void cancel() {
        matter_bottom_bar.setVisibility(View.GONE);

        for (int i=0;i<matterAdapter.getData().size();i++)
        {
            MySection item = matterAdapter.getData().get(i);
            MessageListVO.DataListBean bean = (MessageListVO.DataListBean) item.t;
            if(bean != null){
                bean.setEdit(false);
                bean.setSelected(false);
            }
        }
        matterAdapter.notifyDataSetChanged();
    }

    @Override
    public void edit() {
        matter_bottom_bar.setVisibility(View.VISIBLE);

        for (int i=0;i<matterAdapter.getData().size();i++)
        {
            MySection item = matterAdapter.getData().get(i);
            MessageListVO.DataListBean bean = (MessageListVO.DataListBean) item.t;
            if(bean != null){
                bean.setEdit(true);
                bean.setSelected(false);
            }
        }
        matterAdapter.notifyDataSetChanged();
    }

    @Override
    public void selectAll() {
        for (int i=0;i<matterAdapter.getData().size();i++)
        {
            MySection item = matterAdapter.getData().get(i);
            MessageListVO.DataListBean bean = (MessageListVO.DataListBean) item.t;
            if(bean != null){
                bean.setSelected(true);
            }
        }
        matterAdapter.notifyDataSetChanged();
    }

    @Override
    public void keyPointBottom() {
        String ids = "";
        for (int i=0;i<matterAdapter.getData().size();i++)
        {
            MySection item = matterAdapter.getData().get(i);
            MessageListVO.DataListBean bean = (MessageListVO.DataListBean) item.t;
            if(bean!= null && bean.getSelected())
            {
                ids += bean.getId() + ",";
            }
        }
        if(StringUtils.isSpace(ids))
        {
            ToastUtils.showShortToast("请勾选");
        }else {
            mPresenter.importance(ids.substring(0,ids.length()-1),"1");
        }
    }

    @Override
    public void importanceSuccess() {
        doQuert();
    }

    @Override
    public void lockBottom() {
        String ids = "";
        for (int i=0;i<matterAdapter.getData().size();i++)
        {
            MySection item = matterAdapter.getData().get(i);
            MessageListVO.DataListBean bean = (MessageListVO.DataListBean) item.t;
            if(bean!= null && bean.getSelected())
            {
                ids += bean.getId() + ",";
            }
        }
        if(StringUtils.isSpace(ids))
        {
            ToastUtils.showShortToast("请勾选");
        }else {
            mPresenter.lock(ids.substring(0,ids.length()-1),"1");
        }
    }

    @Override
    public void lockSuccess() {
        doQuert();
    }

    @Override
    public void sureBottom() {

    }

    @Override
    public void deleteBottom() {
        String ids = "";
        for (int i=0;i<matterAdapter.getData().size();i++)
        {
            MySection item = matterAdapter.getData().get(i);
            MessageListVO.DataListBean bean = (MessageListVO.DataListBean) item.t;
            if(bean!= null &&bean.getSelected())
            {
                ids += bean.getId() + ",";
            }
        }
        if(StringUtils.isSpace(ids))
        {
            ToastUtils.showShortToast("请勾选");
        }else {
            mPresenter.delete(ids.substring(0,ids.length()-1));
        }
    }

    @Override
    public void deleteSuccess() {
        doQuert();
    }

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {
        /**
         * 参数说明
         * @param v 被监听的对象
         * @param actionId  动作标识符,如果值等于EditorInfo.IME_NULL，则回车键被按下。
         * @param event    如果由输入键触发，这是事件；否则，这是空的(比如非输入键触发是空的)。
         * @return 返回你的动作
         */
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                doQuert();
            }
            return false;
        }
    };


    private void doQuert(){
        mPresenter.getMessageList(matter_edit.getText().toString());
    }

    @Override
    public void responeError(String errorMsg) {
        ToastUtils.showShortToast("网络异常,请重试");
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    /**
     * 打开新Activity
     *
     * @param context
     * @return
     */
    public static Intent newInstance(Context context) {
        Intent intent = new Intent(context, MatterActivity.class);
        return intent;
    }


    public static List<MySection> getSampleData(List<MessageListVO.DataListBean> dataListBeanList) {
        List<MySection> list = new ArrayList<>();

        HashMap<String,String> hashMap = new HashMap<String,String>();

        for (int i=0;i<dataListBeanList.size();i++){

            MessageListVO.DataListBean bean = dataListBeanList.get(i);
            String date = bean.getSendTime().split("\\s+")[0];
            if(hashMap.get(date) == null){
                //创建header
                list.add(new MySection(true, date, true));
                hashMap.put(date,date);
            }
            bean.setEdit(false);
            bean.setSelected(false);

            list.add(new MySection(bean));
        }
        return list;
    }

}
